{% extends 'web/template.html' %}

{% block title %}线路1 - 首页{% endblock %}

{% block head %}
<!-- 预加载字体文件 -->
<link rel="preload" href="/static/layui/font/iconfont.woff2?v=282" as="font" type="font/woff2" crossorigin>

<style>
    /* 使用系统默认字体作为备选方案 */
    @font-face {
        font-family: 'layui-icon';
        src: url('/static/layui/font/iconfont.woff2?v=282') format('woff2'),
            url('/static/layui/font/iconfont.woff?v=282') format('woff'),
            url('/static/layui/font/iconfont.ttf?v=282') format('truetype');
        font-display: swap;
        /* 使用 swap 策略加快显示速度 */
    }

    /* 加载动画使用系统图标代替 Layui 图标 */
    .loading-spinner {
        display: inline-block;
        width: 30px;
        height: 30px;
        border: 3px solid #f3f3f3;
        border-top: 3px solid #1E9FFF;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        0% {
            transform: rotate(0deg);
        }

        100% {
            transform: rotate(360deg);
        }
    }

    /* 修改内容网格布局，使用响应式设计 */
    .content-grid {
        display: grid;
        gap: 15px;
        /* 默认移动端布局：两列 */
        grid-template-columns: repeat(2, 1fr);
    }

    /* 平板设备：3列 */
    @media screen and (min-width: 768px) {
        .content-grid {
            grid-template-columns: repeat(3, 1fr);
        }
    }

    /* 桌面设备：4列 */
    @media screen and (min-width: 1024px) {
        .content-grid {
            grid-template-columns: repeat(4, 1fr);
        }
    }

    /* 大屏设备：5列 */
    @media screen and (min-width: 1440px) {
        .content-grid {
            grid-template-columns: repeat(5, 1fr);
        }
    }

    /* 优化卡片样式 */
    .content-card {
        background: #fff;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        transition: all 0.3s;
        /* 添加最小宽度确保内容不会过于拥挤 */
        min-width: 140px;
        cursor: pointer;
    }

    .content-image {
        width: 100%;
        /* 根据屏幕宽度调整图片高度 */
        aspect-ratio: 3/4;
        object-fit: cover;
    }

    .content-info {
        padding: 10px;
    }

    .content-title {
        font-size: 13px;
        line-height: 1.4;
        color: #333;
        /* 限制标题最多显示2行 */
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;

        /* 移动端优化：调整字体大小 */
        @media screen and (max-width: 767px) {
            font-size: 12px;
        }
    }

    /* 修改分类样式 */
    .category-list {
        display: flex;
        gap: 8px;
        margin-bottom: 15px;
        flex-wrap: wrap;
        padding: 0 5px;
    }

    .category-item {
        padding: 6px 12px;
        border-radius: 4px;
        cursor: pointer;
        background: #f0f0f0;
        transition: all 0.3s;
        font-size: 13px;
        white-space: nowrap;
        position: relative;
        overflow: hidden;
    }

    /* 添加高亮样式 */
    .category-item.active {
        background: #1E9FFF;
        color: #fff;
        font-weight: 500;
    }

    /* 添加点击涟漪效果 */
    .category-item:active::after {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        width: 100%;
        height: 100%;
        background: rgba(255, 255, 255, 0.3);
        border-radius: 50%;
        transform: translate(-50%, -50%) scale(0);
        animation: ripple 0.6s linear;
    }

    @keyframes ripple {
        to {
            transform: translate(-50%, -50%) scale(2);
            opacity: 0;
        }
    }

    /* 悬停效果 */
    .category-item:hover {
        background: #e0e0e0;
    }

    .category-item.active:hover {
        background: #1890ff;
    }

    /* 容器边距响应式调整 */
    .container {
        padding: 15px;
        max-width: 1400px;
        margin: 0 auto;
    }

    @media screen and (max-width: 767px) {
        .container {
            padding: 10px;
        }
    }

    /* 优化分页在移动端的显示 */
    .pagination {
        margin-top: 20px;
        text-align: center;
    }

    @media screen and (max-width: 767px) {

        .layui-laypage a,
        .layui-laypage span {
            padding: 0 10px;
            margin: 0 2px;
        }
    }

    /* 搜索框容器 */
    .search-container {
        margin-bottom: 20px;
        padding: 0 5px;
    }

    .search-box {
        display: flex;
        gap: 10px;
        max-width: 500px;
        margin: 0 auto;
    }

    /* 搜索输入框 */
    .search-input {
        flex: 1;
        padding: 8px 15px;
        border: 1px solid #e0e0e0;
        border-radius: 4px;
        font-size: 14px;
        transition: all 0.3s;
        outline: none;
    }

    .search-input:focus {
        border-color: #1E9FFF;
        box-shadow: 0 0 0 2px rgba(30, 159, 255, 0.1);
    }

    /* 搜索按钮 */
    .search-button {
        padding: 8px 20px;
        background: #1E9FFF;
        color: #fff;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s;
        font-size: 14px;
    }

    .search-button:hover {
        background: #0d8aee;
    }

    /* 搜索结果提示 */
    .search-result-tip {
        margin: 10px 0;
        padding: 0 5px;
        color: #666;
        font-size: 14px;
    }

    .search-result-tip .keyword {
        color: #1E9FFF;
        font-weight: 500;
    }

    .clear-search {
        color: #1E9FFF;
        cursor: pointer;
        margin-left: 10px;
    }

    .clear-search:hover {
        text-decoration: underline;
    }

    @media screen and (max-width: 767px) {
        .search-box {
            gap: 8px;
        }

        .search-input {
            padding: 6px 12px;
            font-size: 13px;
        }

        .search-button {
            padding: 6px 15px;
            font-size: 13px;
        }
    }

    /* 添加页码跳转样式 */
    .page-jump {
        display: inline-flex;
        align-items: center;
        margin-left: 10px;
        vertical-align: top;
    }

    .page-jump input {
        width: 50px;
        height: 30px;
        margin: 0 5px;
        text-align: center;
        border: 1px solid #e2e2e2;
        border-radius: 2px;
    }

    .page-jump button {
        height: 30px;
        padding: 0 10px;
        background-color: #1E9FFF;
        color: #fff;
        border: none;
        border-radius: 2px;
        cursor: pointer;
        transition: all 0.3s;
    }

    .page-jump button:hover {
        background-color: #0d8aee;
    }

    /* 移动端适配 */
    @media screen and (max-width: 767px) {
        .page-jump {
            margin-top: 10px;
            display: flex;
            justify-content: center;
            width: 100%;
        }
    }
</style>
{% endblock %}

{% block content %}
{% include 'web/components/线路选择.html' %}

<div class="container">
    <!-- 搜索框 -->
    <div class="search-container">
        <div class="search-box">
            <input type="text" class="search-input" id="searchInput" placeholder="请输入关键词搜索..."
                onkeyup="handleSearchKeyup(event)">
            <button class="search-button" onclick="handleSearch()">搜索</button>
        </div>
        <!-- 搜索结果提示 -->
        <div class="search-result-tip" id="searchTip" style="display: none;">
            搜索"<span class="keyword" id="searchKeyword"></span>"的结果
            <span class="clear-search" onclick="clearSearch()">清除搜索</span>
        </div>
    </div>

    <!-- 分类列表 -->
    <div class="category-list" id="categoryList"></div>

    <!-- 内容列表 -->
    <div class="content-grid" id="contentList"></div>

    <!-- 加载动画 -->
    <div class="loading" id="loading" style="display: none;">
        <div class="loading-spinner"></div>
    </div>

    <!-- 分页 -->
    <div id="pagination" class="pagination"></div>
</div>
{% endblock %}

{% block script %}
{% include 'web/line2/解密模块.html' %}
<script>
    let currentCategory = null;
    let currentPage = 1;
    let currentKeyword = ''; // 添加搜索关键词变量
    // 初始化
    window.onload = function () {
        loadCategories();
    };

    // 加载分类
    async function loadCategories() {
        try {
            showLoading();
            const response = await axios.get('api/scraper/hei_liao/line2/get_category/');
            hideLoading();

            if (response.data.code === 0) {
                const categories = response.data.data;

                // 如果没有当前分类，设置第一个为当前分类
                if (!currentCategory && categories.length > 0) {
                    currentCategory = categories[0];
                }

                renderCategories(categories);

                // 默认选中第一个分类
                if (categories.length > 0) {
                    selectCategory(currentCategory || categories[0]);
                }
            } else {
                layer.msg('获取分类失败：' + response.data.message);
            }
        } catch (error) {
            hideLoading();
            layer.msg('获取分类失败：' + error.message);
        }
    }

    // 渲染分类
    function renderCategories(categories) {
        const categoryList = document.getElementById('categoryList');
        categoryList.innerHTML = categories.map(category => {
            const isActive = currentCategory && currentCategory.category_url === category.category_url;
            return `
            <div class="category-item ${isActive ? 'active' : ''}" 
                 onclick='handleCategoryClick(${JSON.stringify(category).replace(/'/g, "&#39;")})'>
                ${category.category_name}
            </div>
        `;
        }).join('');
    }

    // 处理分类点击
    function handleCategoryClick(category) {
        selectCategory(category);
    }

    // 选择分类
    function selectCategory(category) {
        currentCategory = category;
        currentPage = 1;

        // 更新所有分类的样式
        document.querySelectorAll('.category-item').forEach(item => {
            if (item.textContent.trim() === category.category_name) {
                item.classList.add('active');
            } else {
                item.classList.remove('active');
            }
        });

        // 加载该分类的数据
        loadCategoryData();
    }

    // 加载分类数据
    async function loadCategoryData() {
        // 如果有搜索关键词，执行搜索
        if (currentKeyword) {
            await searchContent();
            return;
        }

        if (!currentCategory) return;

        try {
            showLoading();
            const response = await axios.get('api/scraper/hei_liao/line2/get_sub_category/', {
                params: {
                    page: currentPage,
                    category_url: currentCategory.category_url
                }
            });
            hideLoading();

            if (response.data.code === 0) {
                renderContent(response.data.data);
                renderPagination(response.data.data.page_info);
            } else {
                layer.msg('获取数据失败：' + response.data.message);
            }
        } catch (error) {
            hideLoading();
            layer.msg('获取数据失败：' + error.message);
        }
    }

    // 修改渲染内容函数
    function renderContent(data) {
        const contentList = document.getElementById('contentList');
        contentList.innerHTML = data.sub_category_list.map((item, index) => `
            <div class="content-card" onclick="viewDetail('${item.sub_category_item_url}')">
                <img class="content-image" 
                     id="content-image-${index}"
                     alt="${item.sub_category_item_name}"
                     style="opacity: 0; transition: opacity 0.3s;">
                <div class="content-info">
                    <div class="content-title">${item.sub_category_item_name}</div>
                </div>
            </div>
        `).join('');

        // 对每张图片进行解密处理
        data.sub_category_list.forEach((item, index) => {
            const imgElement = document.getElementById(`content-image-${index}`);
            
            // 直接调用 loadBackgroundImage 解密图片
            loadBackgroundImage(item.sub_category_item_cover, imgElement);
            // 监听图片加载完成事件
            imgElement.onload = function () {
                imgElement.style.opacity = '1';
            };
        });
    }

    // 修改渲染分页函数
    function renderPagination(pageInfo) {
        layui.use('laypage', function () {
            const laypage = layui.laypage;
            laypage.render({
                elem: 'pagination',
                count: pageInfo.total_pages * 10,
                curr: pageInfo.current_page,
                limit: 10,
                // 添加页码跳转功能
                layout: ['count', 'prev', 'page', 'next', 'skip'],
                jump: function (obj, first) {
                    if (!first) {
                        // 验证页码范围
                        if (obj.curr > 0 && obj.curr <= pageInfo.total_pages) {
                            currentPage = obj.curr;
                            loadCategoryData();
                        } else {
                            layer.msg('请输入有效的页码', {
                                icon: 2,
                                time: 2000
                            });
                        }
                    }
                }
            });
        });
    }

    // 查看详情
    function viewDetail(url) {
        // 将文章 URL 编码后作为参数传递给详情页
        window.location.href = `/web/line2/detail/?article_url=${encodeURIComponent(url)}`;
    }

    // 显示加载
    function showLoading() {
        document.getElementById('loading').style.display = 'block';
    }

    // 隐藏加载
    function hideLoading() {
        document.getElementById('loading').style.display = 'none';
    }

    // 处理搜索按钮点击
    function handleSearch() {
        const keyword = document.getElementById('searchInput').value.trim();
        if (keyword) {
            currentKeyword = keyword;
            currentPage = 1;
            searchContent();

            // 显示搜索提示
            const searchTip = document.getElementById('searchTip');
            const searchKeyword = document.getElementById('searchKeyword');
            searchKeyword.textContent = keyword;
            searchTip.style.display = 'block';

            // 隐藏分类列表
            document.getElementById('categoryList').style.display = 'none';
        }
    }

    // 处理搜索框回车
    function handleSearchKeyup(event) {
        if (event.key === 'Enter') {
            handleSearch();
        }
    }

    // 清除搜索
    function clearSearch() {
        currentKeyword = '';
        document.getElementById('searchInput').value = '';
        document.getElementById('searchTip').style.display = 'none';
        document.getElementById('categoryList').style.display = 'flex';

        // 恢复到当前分类的内容
        if (currentCategory) {
            loadCategoryData();
        }
    }

    // 搜索内容
    async function searchContent() {
        try {
            showLoading();
            const response = await axios.get('api/scraper/hei_liao/line2/search/', {
                params: {
                    keyword: currentKeyword,
                    page: currentPage
                }
            });

            if (response.data.code === 0) {
                renderContent(response.data.data);
                renderPagination(response.data.data.page_info);
            } else {
                layer.msg('搜索失败：' + response.data.message);
            }
        } catch (error) {
            layer.msg('搜索失败：' + error.message);
        } finally {
            hideLoading();
        }
    }
</script>
{% endblock %}